/**
 * 
 */
package cn.bblocks.cacheTest.suport;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qiniu.util.Md5;

import cn.hutool.core.codec.Base62;



/**
 * @author JZHAO
 * 
 */
public class StringUtil {
	
	
	/** 空字符串。 */
    public static final String EMPTY_STRING = "";
	
	/**
	 * 是否为数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		if (str.matches("\\d*")) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 字符串是否为空
	 * @param str
	 * @return
	 */
	public static boolean isNull(String str) {
		if (str == null || str.length() <= 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
     * 比较两个字符串（大小写敏感）。
     * <pre>
     * StringUtil.equals(null, null)   = true
     * StringUtil.equals(null, "abc")  = false
     * StringUtil.equals("abc", null)  = false
     * StringUtil.equals("abc", "abc") = true
     * StringUtil.equals("abc", "ABC") = false
     * </pre>
     *
     * @param str1 要比较的字符串1
     * @param str2 要比较的字符串2
     *
     * @return 如果两个字符串相同，或者都是<code>null</code>，则返回<code>true</code>
     */
    public static boolean equals(String str1, String str2) {
        if (str1 == null) {
            return str2 == null;
        }

        return str1.equals(str2);
    }

    /**
     * 比较两个字符串（大小写不敏感）。
     * <pre>
     * StringUtil.equalsIgnoreCase(null, null)   = true
     * StringUtil.equalsIgnoreCase(null, "abc")  = false
     * StringUtil.equalsIgnoreCase("abc", null)  = false
     * StringUtil.equalsIgnoreCase("abc", "abc") = true
     * StringUtil.equalsIgnoreCase("abc", "ABC") = true
     * </pre>
     *
     * @param str1 要比较的字符串1
     * @param str2 要比较的字符串2
     *
     * @return 如果两个字符串相同，或者都是<code>null</code>，则返回<code>true</code>
     */
    public static boolean equalsIgnoreCase(String str1, String str2) {
        if (str1 == null) {
            return str2 == null;
        }

        return str1.equalsIgnoreCase(str2);
    }

    /**
     * 检查字符串是否是空白：<code>null</code>、空字符串<code>""</code>或只有空白字符。
     * <pre>
     * StringUtil.isBlank(null)      = true
     * StringUtil.isBlank("")        = true
     * StringUtil.isBlank(" ")       = true
     * StringUtil.isBlank("bob")     = false
     * StringUtil.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果为空白, 则返回<code>true</code>
     */
    public static boolean isBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查字符串是否不是空白：<code>null</code>、空字符串<code>""</code>或只有空白字符。
     * <pre>
     * StringUtil.isBlank(null)      = false
     * StringUtil.isBlank("")        = false
     * StringUtil.isBlank(" ")       = false
     * StringUtil.isBlank("bob")     = true
     * StringUtil.isBlank("  bob  ") = true
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果为空白, 则返回<code>true</code>
     */
    public static boolean isNotBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return false;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查字符串是否为<code>null</code>或空字符串<code>""</code>。
     * <pre>
     * StringUtil.isEmpty(null)      = true
     * StringUtil.isEmpty("")        = true
     * StringUtil.isEmpty(" ")       = false
     * StringUtil.isEmpty("bob")     = false
     * StringUtil.isEmpty("  bob  ") = false
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果为空, 则返回<code>true</code>
     */
    public static boolean isEmpty(String str) {
        return ((str == null) || (str.length() == 0));
    }

    /**
     * 检查字符串是否不是<code>null</code>和空字符串<code>""</code>。
     * <pre>
     * StringUtil.isEmpty(null)      = false
     * StringUtil.isEmpty("")        = false
     * StringUtil.isEmpty(" ")       = true
     * StringUtil.isEmpty("bob")     = true
     * StringUtil.isEmpty("  bob  ") = true
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果不为空, 则返回<code>true</code>
     */
    public static boolean isNotEmpty(String str) {
        return ((str != null) && (str.length() > 0));
    }

    /**
     * 在字符串中查找指定字符串，并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到，则返回<code>-1</code>。
     * <pre>
     * StringUtil.indexOf(null, *)          = -1
     * StringUtil.indexOf(*, null)          = -1
     * StringUtil.indexOf("", "")           = 0
     * StringUtil.indexOf("aabaabaa", "a")  = 0
     * StringUtil.indexOf("aabaabaa", "b")  = 2
     * StringUtil.indexOf("aabaabaa", "ab") = 1
     * StringUtil.indexOf("aabaabaa", "")   = 0
     * </pre>
     *
     * @param str 要扫描的字符串
     * @param searchStr 要查找的字符串
     *
     * @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到，则返回<code>-1</code>
     */
    public static int indexOf(String str, String searchStr) {
        if ((str == null) || (searchStr == null)) {
            return -1;
        }

        return str.indexOf(searchStr);
    }

    /**
     * 在字符串中查找指定字符串，并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到，则返回<code>-1</code>。
     * <pre>
     * StringUtil.indexOf(null, *, *)          = -1
     * StringUtil.indexOf(*, null, *)          = -1
     * StringUtil.indexOf("", "", 0)           = 0
     * StringUtil.indexOf("aabaabaa", "a", 0)  = 0
     * StringUtil.indexOf("aabaabaa", "b", 0)  = 2
     * StringUtil.indexOf("aabaabaa", "ab", 0) = 1
     * StringUtil.indexOf("aabaabaa", "b", 3)  = 5
     * StringUtil.indexOf("aabaabaa", "b", 9)  = -1
     * StringUtil.indexOf("aabaabaa", "b", -1) = 2
     * StringUtil.indexOf("aabaabaa", "", 2)   = 2
     * StringUtil.indexOf("abc", "", 9)        = 3
     * </pre>
     *
     * @param str 要扫描的字符串
     * @param searchStr 要查找的字符串
     * @param startPos 开始搜索的索引值，如果小于0，则看作0
     *
     * @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到，则返回<code>-1</code>
     */
    public static int indexOf(String str, String searchStr, int startPos) {
        if ((str == null) || (searchStr == null)) {
            return -1;
        }

        // JDK1.3及以下版本的bug：不能正确处理下面的情况
        if ((searchStr.length() == 0) && (startPos >= str.length())) {
            return str.length();
        }

        return str.indexOf(searchStr, startPos);
    }

    /**
     * 取指定字符串的子串。
     * 
     * <p>
     * 负的索引代表从尾部开始计算。如果字符串为<code>null</code>，则返回<code>null</code>。
     * <pre>
     * StringUtil.substring(null, *, *)    = null
     * StringUtil.substring("", * ,  *)    = "";
     * StringUtil.substring("abc", 0, 2)   = "ab"
     * StringUtil.substring("abc", 2, 0)   = ""
     * StringUtil.substring("abc", 2, 4)   = "c"
     * StringUtil.substring("abc", 4, 6)   = ""
     * StringUtil.substring("abc", 2, 2)   = ""
     * StringUtil.substring("abc", -2, -1) = "b"
     * StringUtil.substring("abc", -4, 2)  = "ab"
     * </pre>
     * </p>
     *
     * @param str 字符串
     * @param start 起始索引，如果为负数，表示从尾部计算
     * @param end 结束索引（不含），如果为负数，表示从尾部计算
     *
     * @return 子串，如果原始串为<code>null</code>，则返回<code>null</code>
     */
    public static String substring(String str, int start, int end) {
        if (str == null) {
            return null;
        }

        if (end < 0) {
            end = str.length() + end;
        }

        if (start < 0) {
            start = str.length() + start;
        }

        if (end > str.length()) {
            end = str.length();
        }

        if (start > end) {
            return EMPTY_STRING;
        }

        if (start < 0) {
            start = 0;
        }

        if (end < 0) {
            end = 0;
        }

        return str.substring(start, end);
    }
    
    /**
     * 截取字符
     * @param str
     * @param limit
     * @return
     */
    public static String substringLimit(String str,int limit) {
    	if(StringUtil.isNotEmpty(str) && str.length()>limit)
    		return str.substring(0, limit);
    	else
    		return str;
    }
    
    /**
     * 检查字符串中是否包含指定的字符串。如果字符串为<code>null</code>，将返回<code>false</code>。
     * <pre>
     * StringUtil.contains(null, *)     = false
     * StringUtil.contains(*, null)     = false
     * StringUtil.contains("", "")      = true
     * StringUtil.contains("abc", "")   = true
     * StringUtil.contains("abc", "a")  = true
     * StringUtil.contains("abc", "z")  = false
     * </pre>
     *
     * @param str 要扫描的字符串
     * @param searchStr 要查找的字符串
     *
     * @return 如果找到，则返回<code>true</code>
     */
    public static boolean contains(String str, String searchStr) {
        if ((str == null) || (searchStr == null)) {
            return false;
        }

        return str.indexOf(searchStr) >= 0;
    }
    
    
    /**
     * 查找首数字
     * 
     * “00001”=>0
     * "a001"=>
     * 
     * @param str 
     * @return
     */
    public static int firstNumIndex(String str){
    	if(str == null || "".equals(str))
    		return -1;
    	
    	
    	
    	
    	for(int p=0;p<str.length();p++){
    		
    		if( StringUtil.isNumeric(String.valueOf(str.charAt(p))) )
    			return p; 
    	}
    	return -1;
    }
    
    
 public static String leftPadding(String str,int length,String  padding){
    	
    	
    	str = String.format("%"+length+"s",str);
    	
    	if(" ".equals(padding))
    		return str;
    	else
    		return str.replace(" ", padding);
    }
    
    public static String rightPadding(String str,int length,String  padding){
    	
    	
    	str = String.format("%-"+length+"s",str);
    	if(" ".equals(padding))
    		return str;
    	else
    		return str.replace(" ", padding);
    }
    
    
    public static Map<String, String> sortMapByKeyUp(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
     
        Map<String, String> sortMap = new TreeMap<String, String>(
                new Comparator<String>() {
                  public int compare(String obj1, String obj2) {
                    // 升序排序
                	  return obj1.compareTo(obj2);
                  }
                });
        

        sortMap.putAll(map);
        return sortMap;
    }
    
    public static Map<String, String> sortMapByKeyDown(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
     
        Map<String, String> sortMap = new TreeMap<String, String>(
                new Comparator<String>() {
                  public int compare(String obj1, String obj2) {
                    // 升序排序
                	  return obj2.compareTo(obj1);
                  }
                });
        

        sortMap.putAll(map);
        return sortMap;
    }
    
    /**
	 * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * 
	 * @param params
	 *            需要排序并参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	public static String createLinkString(Map<String, String> params) {

		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);

		String prestr = "";

		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);

			if (i == keys.size() - 1) {
				prestr = prestr + key + "=" + value;
			} else {
				prestr = prestr + key + "=" + value + "&";
			}
		}

		return prestr;
	}
	
	/**
	 * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串(为空的不要)
	 * 
	 * @param params
	 *            需要排序并参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	public static String createLinkString2(Map<String, String> params) {

		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);

		String prestr = "";

		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			
//			if(StringUtil.isEmpty(value))
//				continue;
			
			if (i == keys.size() - 1) {
				prestr = prestr + key + "=" + value;
			} else {
				prestr = prestr + key + "=" + value + "&";
			}
		}

		return prestr;
	}
	
	private static Random random = new Random();  
	public static String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	       
	    StringBuffer sb = new StringBuffer();     
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }   
	
	  public static String mapToXml(Map<String,Object> param) {
	        StringBuilder sb = new StringBuilder("<xml>");

	        for(Map.Entry<String, Object> entry : param.entrySet()) {
	            sb.append("<").append(entry.getKey()).append("><![CDATA["). append(entry.getValue()).append("]]></").append(entry.getKey()).append(">");
	        }
	        sb.append("</xml>");
	        return sb.toString();
	  }
	  
	  /**
	     * IceWee 2013.07.19
	     * 获取本地IP列表（针对多网卡情况）
	     *
	     * @return
	     */
	    public static List<String> getLocalIPList() {
	        List<String> ipList = new ArrayList<String>();
	        try {
	            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
	            NetworkInterface networkInterface;
	            Enumeration<InetAddress> inetAddresses;
	            InetAddress inetAddress;
	            String ip;
	            while (networkInterfaces.hasMoreElements()) {
	                networkInterface = networkInterfaces.nextElement();
	                inetAddresses = networkInterface.getInetAddresses();
	                while (inetAddresses.hasMoreElements()) {
	                    inetAddress = inetAddresses.nextElement();
	                    if (inetAddress != null && inetAddress instanceof Inet4Address 
	                    		&& !inetAddress.isLoopbackAddress()) { // IPV4
	                        ip = inetAddress.getHostAddress();
	                        ipList.add(ip);
	                    }
	                }
	            }
	        } catch (SocketException e) {
	            e.printStackTrace();
	        }
	        return ipList;
	    }
	    
	    /**
	     * 随机生成数字校验码
	     * @param len 长度
	     * @return
	     */
	    public static String getLimitLenNum(int len) {
	    	String max = "89999999999";
	    	String add = "10000000000";
	    	
	    	int maxValue = Integer.parseInt(max.substring(0,len));
	    	int addValue = Integer.parseInt(add.substring(0,len));
	    	String verifyCode = String
	                .valueOf(new Random().nextInt(maxValue) + addValue);//生成短信验证码
	    	return verifyCode;
	    }
	    
	    /**
		 * 生成token
		 * @return
		 */
		public static String GetGUID()
		{
			return UUID.randomUUID().toString().replace("-", "");
		}

		
		
		/**
		 * 匹配数字
		 * @param text
		 * @return
		 */
		public static List<String> matcherNumbers(String text) {
			Pattern p = Pattern.compile("\\d+(\\.\\d+){0,1}");
			Matcher matcher = p.matcher(text);
			
	        
			List<String> list = new ArrayList();
			while (matcher.find()) {
		      
		        list.add(matcher.group());
		    }
			return list;
		}
		
		public static byte[] str2bytes(String str) {
			if(isNull(str))
				return null;
			try {
				return str.getBytes("utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				return str.getBytes();
			}
		}
	    
    public static void main(String[] args){
    	String a = "ab中001";
    	
    	System.out.println(StringUtil.isNumeric(a));
    	
    	
    	System.out.println(StringUtil.firstNumIndex(a));
    	
    	System.out.println (a.substring(StringUtil.firstNumIndex(a),a.length()) );
    	
    	Map<String,String> one = new HashMap();
    	
    	one.put("a", "");
    	one.put("c", "");
    	one.put("b", "");
    	one.put("d", "");
    	
    	String aaa = "210000";
    	System.out.println(StringUtil.leftPadding(aaa,5,"0"));
    	
//    	one = sortMapByKey(one);
    	
//    	Set<String> keySet = one.keySet();
//
//    	Iterator<String> iter = keySet.iterator();
//        while (iter.hasNext()) {
//          String key = iter.next();
//          System.out.println(key + ":" + one.get(key));
//        }
    	long b = System.currentTimeMillis();
    	int tt = 1;
    	int i = 0;
    	while((i++)<tt) {
    		
    	
//    	String verifyCode = String
//                .valueOf(new Random().nextInt(8999) + 1000);//生成短信验证码
//    	
//    	System.out.println(getLimitLenNum(4));
    	
    	;
    	String rStr = getRandomString(32);
    	System.out.println(rStr);
    	}
    	
    	List<String> list = matcherNumbers("原价12.5元，是12元");
    	for(String ones:list) {
    		System.out.println(ones);
    	}
    	
    	System.out.println("tt:"+(System.currentTimeMillis() - b));
    	
    	String regEx = "\\d+(\\.\\d+){0,1}";//匹配指定范围内的数字
    	
//    	body: {activityId: 4, nickName: "Love Life", num: 2,…}
//    	activityId: 4
//    	nickName: "Love Life"
//    	num: 2
//    	prize: {code: "lq", createBy: "", id: 3, lastModifiedBy: "", num: 1, prizeDesc: "龙躯",…}
//    	code: "lq"
//    	createBy: ""
//    	id: 3
//    	lastModifiedBy: ""
//    	num: 1
//    	prizeDesc: "龙躯"
//    	prizeImg: "http://img.bblocks.cn/e5b2c417c29c4a5da0af9a6a79ec5075.png"
//    	prizeImg2: "http://img.bblocks.cn/07a60c09f0304e21ae5af936bfe485a2.png"
//    	prizeName: "龙身"
//    	prizeType: 1
//    	realNum: 1
//    	status: 1
//    	prizeId: 3
//    	serialNumber: "AC_1572091421985"
//    	sign: "78a575be31a07ed44d3f2e9d43fe9ac9"
//    	type: 1
//    	userId: 75194
//    	error: 0
//    	serverInfo: "172.17.0.1(8089)"
    	String s = 3+""+75194+""+2+""+"AC_1572091421985"+3+""+1+"123456654321";
    	System.out.println(s);
    	String mysign =	Md5.md5(StringUtil.str2bytes((s)));
    	System.out.println(mysign);
    	 mysign =	Md5.md5(StringUtil.str2bytes((3+75194+2+"AC_1572091421985"+3+1+"123456654321")));
    	 System.out.println(mysign);
    	 
    	 s= "&userId=12&page=0&size=10";
    	 s ="1iDrGERIimWEUjQqG2JVLMJYiv6WdQn5OK";
    	 
    	 System.out.println("Base62:"+Base62.encode(s));
    }
    
}
